	package com.enlorenz.common.util;

import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * 
 * @author victor
 *
 */
public class DesUtils {
	private static final String Algorithm = "DES"; //定义 加密算法,可用 DES,DESede,Blowfish 
	private static final String DEFAULT_BYTES_CODE="utf-8";
	/**
	 * 加密
	 * @param key 关键字
	 * @param data 数据
	 * @return 加密后的数据
	 */
	public static byte[] encrypt(byte[] key, byte[] data) { 
		try { 
			Security.addProvider(new com.sun.crypto.provider.SunJCE());
			//生成密钥 
			SecretKey deskey = new SecretKeySpec(key, Algorithm); 
			//加密 
			Cipher c1 = Cipher.getInstance(Algorithm); 
			c1.init(Cipher.ENCRYPT_MODE, deskey); 
			return c1.doFinal(data); 
		}catch (Exception e) { 
			throw new RuntimeException(e);
		} 
	} 
	

	
	/**
	 * 解密
	 * @param key 关键字
	 * @param data 数据
	 * @return 解密后的数据
	 */
	public static byte[] decrypt(byte[] key, byte[] data) { 
		try { 
			Security.addProvider(new com.sun.crypto.provider.SunJCE());
			//生成密钥 
			SecretKey deskey = new SecretKeySpec(key, Algorithm); 
			//解密 
			Cipher c1 = Cipher.getInstance(Algorithm); 
			c1.init(Cipher.DECRYPT_MODE, deskey); 
			return c1.doFinal(data); 
		}catch (Exception e) { 
			throw new RuntimeException(e);
		} 
	}
	
	/**
	 * 加密
	 * @param key 关键字
	 * @param data 数据
	 * @return 加密后的数据
	 */
	public static String encrypt(String key,String data){
		byte[] encrypt = encrypt(CodeUtils.hexString2Bytes(key),StringUtils.getBytes(data, DEFAULT_BYTES_CODE));
		return CodeUtils.bytes2HexString(encrypt);
	}

	/**
	 * 解密
	 * @param key 关键字
	 * @param data 数据
	 * @return 解密后的数据
	 */
	public static String decrypt(String key, String data){
		byte[] decrypt = decrypt(CodeUtils.hexString2Bytes(key), CodeUtils.hexString2Bytes(data)); 
		return StringUtils.newString(decrypt, DEFAULT_BYTES_CODE);
	}
	
	
	public static void main(String arg[]){
		
		String str = "org.apache.log4j.DailyRollingFileAppender";
		String strKey = "0002000200020002";
		String s3 = encrypt(strKey,str);
		String s4 = decrypt(strKey,"8E28135D94DF7CC1742E66FD84DC2049CAFDEC2EB229D956F416B99426E5BC112DF3A2A9938E7F0BFBE6F7A31389EB64");
		System.out.println("1."+s3);
		System.out.println("2."+s4);
		
		
	}
}
